/**=========================================================
 * Service: echarts-util.js
 =========================================================*/

 tzadmin.service('EchartsUtils', ['HttpUtils','Utils', 
    function(httpUtils, utils) {
        'use strict';
        
        return {
            /**
             * 指标折线图
             */
            initMetricLineChartObject: function($scope,options) {
                var defaultOptions = {
                    optionModel: 'echartsOption',
                    name: 'chart',
                    showLabel: false,     
                    showLegend: true,
                    showToolbox: false,
                    type: '',
                    params: {},
                    /**
                     * 画图前可以自主修改option
                     */
                    beforeDrawFn: null,
                    /**
                     * 用户判定系列属于哪个y坐标轴
                     */
                    yAxisData: null
                };
                
                var finalOptions = angular.extend(defaultOptions,options);
                
                return {
                    scope: $scope,
                    options: finalOptions,
                    currentParam: finalOptions.params,
                    draw: function(params){
                        var scope = this.scope,
                            options = this.options,
                            yAxisData = options.yAxisData,
                            chart = scope[options.name];
                        this.currentParam = params;
                              
                        if (!utils.isEmpty(chart)){
                            chart.showLoading();
                        }
                            
                        httpUtils.get(utils.getQueryListUrl(),params,
                            function (result) {
                                var columns = result.datas.gridColumns;
                                var datas = result.datas.gridDatas,
                                    chartOption = {};
                                if (datas.length > 0){
                                    var legendData = [],
                                        xAxisData = [],
                                        series = [],
                                        doubleYAxis = !(utils.isEmpty(yAxisData) || utils.isEmpty(yAxisData[0]) || utils.isEmpty(yAxisData[1]));
                                    
                                    //xAxisData
                                    for (var k = 0; k < columns.length; k++){
                                        if (utils.isDateString(columns[k].field)){
                                            xAxisData.push(columns[k].field);
                                        }
                                    }
                                    
                                    //series
                                    var leftDatas = [],rightDatas = [];
                                    for (var i = 0; i < datas.length; i++){
                                        var serieData = [];
                                        for (var j = 0; j < xAxisData.length; j++){							
                                            serieData.push((utils.isEmpty(datas[i][xAxisData[j]]) || datas[i][xAxisData[j]] == '-') ? 0 : (datas[i][xAxisData[j]] + "").replace("%","") / 1);
                                        }
                                        if (doubleYAxis){
                                            if (utils.isArrayContains(yAxisData[0],datas[i].metric_id)){
                                                series.push({
                                                    name: datas[i].metric_name,
                                                    type: 'line',
                                                    data: serieData,
                                                    symbolSize: 8,
                                                    label: {
                                                        normal: {
                                                            show: options.showLabel,
                                                            position: 'top'
                                                        }
                                                    }
                                                });
                                                leftDatas.push(datas[i]);
                                            }else{
                                                series.push({
                                                    name: datas[i].metric_name,
                                                    type: 'line',
                                                    yAxisIndex: 1,
                                                    data: serieData,
                                                    symbolSize: 10,
                                                    label: {
                                                        normal: {
                                                            show: options.showLabel,
                                                            position: 'top'
                                                        }
                                                    }
                                                });
                                                rightDatas.push(datas[i]);
                                            }
                                        }else {
                                            series.push({
                                                name: datas[i].metric_name,
                                                type: 'line',
                                                data: serieData,
                                                symbolSize: 8,
                                                label: {
                                                    normal: {
                                                        show: options.showLabel,
                                                        position: 'top'
                                                    }
                                                }
                                            });
                                        }
                                        
                                        legendData.push(datas[i].metric_name);
                                    }
       
                                    
                                    if (options.type == 'area' || options.type == 'areaStack'){
                                        if (options.type == 'area') {
                                            for (var i = 0; i < series.length; i++){
                                                series[i].itemStyle = {normal: {areaStyle: {type: 'default'}}};
                                            }
                                        }else {
                                            for (var i = 0; i < series.length; i++){
                                                series[i].itemStyle = {normal: {areaStyle: {type: 'default'}}};
                                                series[i].stack = 'stack1';
                                            }
                                        }
                                    }
                                    
                                    //yAxis、grid
                                    var yAxis,grid;
                                    if (doubleYAxis){
                                        yAxis = [
                                            {
                                                type : 'value',
                                                scale: true,
                                                axisLabel: {
                                                    formatter: function (value, index) {
                                                        if (leftDatas[0].show_type == "3"){
                                                            return utils.numberFormat(value) + " %";
                                                        }else if (value > 1000000){
                                                            return utils.numberFormat(value / 1000000) + " M"
                                                        }else {
                                                            return utils.numberFormat(value)
                                                        }
                                                        
                                                    }
                                                }
                                            },
                                            {
                                                type : 'value',
                                                scale: true,
                                                axisLabel: {
                                                    formatter: function (value, index) {
                                                        if (rightDatas[0].show_type == "3"){
                                                            return utils.numberFormat(value) + " %";
                                                        }else if (value > 1000000){
                                                            return utils.numberFormat(value / 1000000) + " M"
                                                        }else {
                                                            return utils.numberFormat(value)
                                                        }
                                                        
                                                    }
                                                }
                                            }
                                        ];
                                        
                                        grid = {
                                            y: 10,
                                            y2: 40,
                                            x: 60,
                                            x2: 80
                                        }
                                    }else{
                                        yAxis = [
                                            {
                                                type : 'value',
                                                scale: true,
                                                axisLabel: {
                                                    formatter: function (value, index) {
                                                        if (datas[0].show_type == "3"){
                                                            return utils.numberFormat(value) + " %";
                                                        }else if (value > 1000000){
                                                            return utils.numberFormat(value / 1000000) + " M"
                                                        }else {
                                                            return utils.numberFormat(value)
                                                        }
                                                        
                                                    }
                                                }
                                            }
                                        ];
                                        
                                        grid = {
                                            y: 10,
                                            y2: 40,
                                            x: 60,
                                            x2: 40
                                        }
                                    }
                                    
                                    if (options.showLegend){
                                        grid.y += 50;
                                    }
                                    
                                    //toolbox
                                    var toolbox = {
                                        show: options.showToolbox,
                                        y: 18,
                                        feature: {
                                            // dataZoom: {show: true},
                                            magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                                            restore: {show: true},
                                            saveAsImage: {show: true}
                                        }
                                    }
                                    
                                    chartOption = {
                                        tooltip: {
                                            trigger: 'axis',
                                            showDelay: 0,
                                            formatter: function (params,ticket,callback) {
                                                var res = '<span>' + params[0].name + '</span><br/>';
                                                for (var i = 0; i < params.length; i++) {
                                                    
                                                    if (datas[i].show_type == "3"){
                                                        res += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + params[i].color + '"></span>' +
                                                                params[i].seriesName + '：' + params[i].value + "%" +
                                                            '<br/>';
                                                    }else{
                                                        res += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + params[i].color + '"></span>' +
                                                                params[i].seriesName + '：' + utils.numberFormat(params[i].value + "") +
                                                            '<br/>';
                                                    }
                                                    
                                                }
            
                                                return res;
                                            }
                                        },
                                        toolbox: toolbox,
                                        grid: grid,
                                        legend: {
                                            show: options.showLegend,
                                            data: legendData,
                                            x: 'left'
                                        },
                                        yAxis: yAxis,
                                        xAxis: {
                                            type: 'category',
                                            data: xAxisData,
                                            boundaryGap: false,
                                            splitLine: false
                                        },
                                        series: series
                                    };
                                }
                                
                                if (options.beforeDrawFn instanceof Function){
                                    options.beforeDrawFn.call(this,chartOption);
                                }
                                
                                scope[options.optionModel] = chartOption;
                            }
                        );
                    }
                }
            },
            /**
             * 维度折线图
             */
            initDimensionLineChartObject: function($scope,options){
                var defaultOptions = {
                    optionModel: 'echartsOption',
                    name: 'chart',
                    dimension: '',
                    showLabel: false,
                    showLegend: true,
                    showToolbox: false,
                    params: {}
                };
                
                var finalOptions = angular.extend(defaultOptions,options);
                
                return {
                    scope: $scope,
                    options: finalOptions,
                    currentParam: finalOptions.params,
                    draw: function(params){
                        var scope = this.scope,
                            options = this.options,
                            chart = scope[options.name];
                        this.currentParam = params;
                        
                        if (!utils.isEmpty(chart)){
                            chart.showLoading();
                        }
                        
                        httpUtils.get(utils.getQueryListUrl(),params,
                            function (result) {
                                var columns = result.datas.gridColumns;
                                var datas = result.datas.gridDatas,
                                    chartOption = {};
                                if (datas.length > 0){
                                    var legendData = [];
                                    var xAxisData = [];
                                    var series = [];
                            
                                    for (var k = 0; k < columns.length; k++){
                                        if (utils.isDateString(columns[k].field)){
                                            xAxisData.push(columns[k].field);
                                        }
                                    }
                                    
                                    for (var i = 0; i < datas.length; i++){
                                        legendData.push(datas[i][options.dimension]);
                                        
                                        var serieData = [];
                                        for (var j = 0; j < xAxisData.length; j++){							
                                            serieData.push((utils.isEmpty(datas[i][xAxisData[j]]) || datas[i][xAxisData[j]] == '-') ? 0 : (datas[i][xAxisData[j]] + "").replace("%","") / 1);
                                        }
                                        
                                        series.push({
                                            name: datas[i][options.dimension],
                                            type: 'line',
                                            yAxisIndex: 0,
                                            data: serieData,
                                            symbolSize: 8,
                                            label: {
                                                normal: {
                                                    show: options.showLabel,
                                                    position: 'top'
                                                }
                                            }
                                        });
                                    }
                                    
                                    //yAxis
                                    var yAxis = [
                                        {
                                            type : 'value',
                                            scale: true
                                        }
                                    ];
                                    
                                    if (datas[0].show_type == "3"){
                                        yAxis[0].axisLabel = {
                                            formatter: '{value} %'
                                        };
                                    }
                                    
                                    //toolbox
                                    var toolbox = {
                                        show: options.showToolbox,
                                        y: 18,
                                        feature: {
                                            // dataZoom: {show: true},
                                            magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                                            restore: {show: true},
                                            saveAsImage: {show: true}
                                        }
                                    }
                                    
                                    //grid
                                    var grid = {
                                        y: 40,
                                        y2: 40,
                                        x: 60,
                                        x2: 40
                                    }
                                    
                                    if (options.showToolbox){
                                        grid.y += 20;
                                    }
                                    
                                    var metricName = datas[0].metric_name;
                                    
                                    chartOption = {
                                        tooltip: {
                                            trigger: 'axis',
                                            showDelay: 0,
                                            formatter: function (params,ticket,callback) {
                                                var res = '<span>' + params[0].name + '</span><br/>';
                                                res += '<span>' + metricName + '</span><br/>';
                                                for (var i = 0; i < params.length; i++) {
                                                    var value = params[i].value + "";
                                                    value = utils.numberFormat(value);
                                                    
                                                    res += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + params[i].color + '"></span>' +
                                                                params[i].seriesName + ' : ' + value + ((datas[i].show_type == "3") ? "%" : "") +
                                                            '<br/>';
                                                }
            
                                                return res;
                                            }
                                        },
                                        calculable: true,
                                        toolbox: toolbox,
                                        grid: grid,
                                        yAxis: yAxis,
                                        xAxis: [
                                            {
                                                type: 'category',
                                                data: xAxisData,
                                                boundaryGap: false,
                                                splitLine: false
                                            }
                                        ],
                                        series: series,
                                        legend: {
                                            show: options.showLegend,
                                            data: legendData,
                                            x: 'left'
                                        }
                                    };
                                }
                            
                                scope[options.optionModel] = chartOption;
                            }
                        );
                    }
                }
            },
            /**
             * 条形图
             * 返回数据格式
             * {
             *      name: y轴值
             *      value: x轴值
             *      title: 系列名
             * }
             */
            initPieChartObject: function($scope,options){
                var defaultOptions = {
                    optionModel: 'echartsOption',
                    params: {},
                    /**
                     * 画图前可以自主修改option
                     */
                    beforeDrawFn: null,
                };

                var finalOptions = angular.extend(defaultOptions,options);

                return {
                    scope: $scope,
                    options: finalOptions,
                    currentParam: finalOptions.params,
                    draw: function(params){
                        var scope = this.scope,
                            options = this.options;
                        this.currentParam = params;

                        httpUtils.get(utils.getQueryListUrl(),params,
                            function (result) {
                                var datas = result.datas.gridDatas,
                                    chartOption = {};;
                                if (datas.length > 0){
                                    var item = {
                                        title: datas[0].title,
                                        legendDatas: [],
                                        serieDatas: []
                                    };

                                    for (var i = 0; i < datas.length; i++) {
                                        item.legendDatas.push(datas[i].name);                
                                        item.serieDatas.push({value:datas[i].value, name:datas[i].name}); 
                                    }

                                    chartOption = {
                                        tooltip: {
                                            trigger: 'item',
                                            formatter: function(params, ticket, callback){
                                                return params.seriesName + '<br>' + params.name + '：' + utils.numberFormat(params.value) + '(' + params.percent + '%)'
                                            }
                                        },
                                        grid: {
                                            bottom: 200
                                        },
                                        series: [{
                                            name: item.title,
                                            type: 'pie',
                                            selectedMode : 'single',
                                            radius: 120,
                                            center: ['50%','50%'],
                                            data: item.serieDatas,
                                            label: {
                                                normal: {
                                                    textStyle: {
                                                        fontSize: 16
                                                    }
                                                }
                                            }
                                        }]
                                    }
                                }

                                scope[options.optionModel] = chartOption;
                            }
                        )
                    }
                }
            },
            /**
             * 条形图
             * 返回数据格式
             * {
             *      name: y轴值
             *      value: x轴值
             *      serie: 系列名
             * }
             */
            initTopBarChartObject: function($scope,options){
                var defaultOptions = {
                    optionModel: 'echartsOption',
                    params: {},
                    /**
                     * 画图前可以自主修改option
                     */
                    beforeDrawFn: null,
                };
                
                var finalOptions = angular.extend(defaultOptions,options);
                
                return {
                    scope: $scope,
                    options: finalOptions,
                    currentParam: finalOptions.params,
                    draw: function(params){
                        var scope = this.scope,
                            options = this.options;
                        this.currentParam = params;
                            
                        httpUtils.get(utils.getQueryListUrl(),params,
                            function (result) {
                                var datas = result.datas.gridDatas,
                                    chartOption = {};;
                                if (datas.length > 0){
                                    
                                    var yAxisData = [];
                                    var seriesData = [];
                                    
                                    for (var i = 0; i < datas.length; i++){
                                        yAxisData.push(datas[i].name);
                                        seriesData.push(datas[i].value);
                                    }
                                    
                                    chartOption = {
                                        tooltip: {
                                            trigger: 'axis',
                                            axisPointer: {
                                                type : 'shadow'
                                            },
                                            showDelay: 0,
                                            formatter: function (params,ticket,callback) {
                                                var res = '<span>' + params[0].name.split("\\n").join(" ") + '</span><br/>';
                                                res += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + params[0].color + '"></span>' +
                                                            params[0].seriesName + '：' + utils.numberFormat(params[0].value + "") +
                                                        '<br/>';
            
                                                return res;
                                            }
                                        },
                                        calculable: true,
                                        xAxis: [
                                            {
                                                type: 'value',
                                                boundaryGap: [0, 0.01],
                                                axisLine: {
                                                    show: false 
                                                }
                                            }
                                        ],
                                        yAxis : [
                                            {
                                                type: 'category',
                                                data: yAxisData,
                                                axisLabel: {
                                                    formatter: function(val){
                                                        return val.split("\\n").join("\n");
                                                    }
                                                },
                                                splitLine: {
                                                    show: false
                                                }
                                            }
                                        ],
                                        series : [
                                            {
                                                name: datas[0].serie,
                                                type: 'bar',
                                                data: seriesData
                                            }
                                        ],
                                        grid: {
                                            y: 20,
                                            y2: 40,
                                            x: 130
                                        }
                                    };
                                    
                                    if (options.beforeDrawFn instanceof Function){
                                        options.beforeDrawFn.call(this,chartOption,datas);
                                    }
                                }

                                scope[options.optionModel] = chartOption;
                            }
                        );
                    }
                }
            },
            /**
             * 地图
             * 返回数据格式
             * {
             *      name: 地区名
             *      value: 值
             *      serie: 系列名
             * }
             * 数据需要倒序排序
             */
            initMapChartObject: function($scope,options){
                var defaultOptions = {
                    optionModel: 'echartsOption',
                    showLabel: true
                };
                
                var finalOptions = angular.extend(defaultOptions,options);
                
                return {
                    scope: $scope,
                    options: finalOptions,
                    currentParam: {},
                    draw: function(params){
                        var scope = this.scope,
                            options = this.options;
                        this.currentParam = params;
                            
                        httpUtils.get(utils.getQueryListUrl(),params,
                            function (result) {
                                var datas = result.datas.gridDatas,
                                    chartOption = {};
                                if (datas.length > 0){
                                    var seriesData = [];
                                    
                                    for (var i = 0; i < datas.length; i++){
                                        seriesData.push({
                                            name: datas[i].name,
                                            value: datas[i].value,
                                            showName: utils.isEmpty(datas[i].show_name) ? datas[i].name : datas[i].show_name
                                        });
                                    }
                                    
                                    chartOption = {
                                        tooltip : {
                                            trigger: 'item',
                                            formatter: function(params, ticket, callback) {
                                                return params.data.showName + '<br>' + params.seriesName + '：' + params.value;
                                            }
                                        },
                                        visualMap: {
                                            min: 0,
                                            max: datas[0].value,
                                            x: 'left',
                                            y: 'bottom',
                                            text:['高','低'],
                                            calculable : true
                                        },
                                        series : [
                                            {
                                                name: datas[0].serie,
                                                type: 'map',
                                                mapType: 'china',
                                                itemStyle: {
                                                    normal: {
                                                        label:{
                                                            show:finalOptions.showLabel
                                                        }
                                                    },
                                                    emphasis: {
                                                        label:{
                                                            show:finalOptions.showLabel
                                                        }
                                                    }
                                                },
                                                data: seriesData
                                            }
                                        ]
                                    };
                                }
                            
                                scope[options.optionModel] = chartOption;
                            }
                        );
                    }
                }
            },
            /**
             * 自定义图
             */
            initChartObject: function($scope,options){
                var defaultOptions = {
                    optionModel: 'echartsOption'
                };
                
                var finalOptions = angular.extend(defaultOptions,options);
                
                return {
                    scope: $scope,
                    options: finalOptions,
                    draw: function(option){
                        this.scope[this.options.optionModel] = option;
                    }
                }
            }
        }
    }
]);
